package org.kotemaru.gae.dstool.client.gui;
import org.apache.commons.beanutils.BeanUtils;
import org.kotemaru.browser.*;
import org.kotemaru.gae.dstool.client.*;
import java.util.*;
import java.io.*;

public class OAuthAction extends ActionBase {
	public static final String OAUTH_PROP = DsToolClient.DSTOOL_PROPS;
	public static final String FINISH = "finish";

	private String appid;
	private String secret;
	private String submit;

	public Navigator execute() throws Exception {

		if (submit == null) {
			Properties props =
				ClientUtil.loadProps(OAUTH_PROP, null, false);
			BeanUtils.copyProperties(this, props);
			return velocity("oauth.vm");
		} else {
			PrintStream backupErr = System.err;
			try {
				System.setErr(new StderrLogger(super.takeBrowserFrame()));
				return doSubmit();
			} finally {
				System.setErr(backupErr);
			}
		}
	}
	private Navigator doSubmit() throws Exception {
		if (!FINISH.equals(submit)) {
			appid = ClientUtil.correntAppid(appid);
			String url =
				GaeOAuthClient.prepare(OAUTH_PROP, appid, secret);
			return redirect(url);
		} else {
			GaeOAuthClient.finish(OAUTH_PROP);
			return velocity("oauth-fin.vm");
		}
	}

	
//-------------------------------------------------------
// Setter/Getter

	public String getAppid() {
		return appid;
	}

	public void setAppid(String appid) {
		this.appid = appid;
	}

	public String getSecret() {
		return secret;
	}

	public void setSecret(String secret) {
		this.secret = secret;
	}

	public String getSubmit() {
		return submit;
	}

	public void setSubmit(String submit) {
		this.submit = submit;
	}

}